package start;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class ADAOImpJDBC extends JdbcDaoSupport implements ADAO {
    private TransactionTemplate transactionTemplate;

    public ADAOImpJDBC() {
        System.out.println("ADAOImpJDBC create..");
    }

    @Override
    public void test() {
        System.out.println("ADAOImpJDBC. test()");
        System.out.println("ADAOImpJDBC. insert");
        this.getJdbcTemplate().update("insert into aTable(name) values(?)", "sasha");
        System.out.println("ADAOImpJDBC. select");
        A a =
            this.getJdbcTemplate().queryForObject("SELECT * from aTable where id=1", new ParameterizedRowMapper<A>() {
                @Override
                public A mapRow(ResultSet rs, int rowNum) throws SQLException {
                    A a = new A();
                    a.setId(rs.getLong(1));
                    a.setName(rs.getString(2));
                    return a;
                }
            });
        System.out.println(a);
    }

    public void test2() {
        System.out.println("ADAOImpJDBC. test2()");
        transactionTemplate.execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                System.out.println(status.isNewTransaction());
                System.out.println(status.isCompleted());
                System.out.println(status.isRollbackOnly());
                System.out.println("ADAOImpJDBC. doInTransaction(" + status + ")");
                getJdbcTemplate().update("insert into aTable(name) values(?)", "rollback3");
                status.setRollbackOnly();
                status.flush();
                System.out.println(status.isCompleted());
                System.out.println(status.isRollbackOnly());
                System.out.println(status.isNewTransaction());
                status.setRollbackOnly();
                throw new RuntimeException();
                //return null;
            }
        });
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public TransactionTemplate getTransactionTemplate() {
        return transactionTemplate;
    }
}
